﻿using BlogDemo.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;

namespace BlogDemo.Infrastructure
{
    public class EfRepositoryContext : RepositoryContext, IEfRepositoryContext
    {
        private IDbContext _context;

        public IDbContext Db { get { return _context; } }
        private IDbContextTransaction _dbTransaction;
        public EfRepositoryContext(IDbContext dbContext)
        {
            this._context = dbContext;
            this.Connection = dbContext.Database.GetDbConnection();
        }

        public override void RegisterNew<TEntity>(TEntity entity)
        {
            Db.Set<TEntity>().Add(entity);
        }

        public override void RegisterModified<TEntity>(TEntity entity)
        {
            Db.Entry<TEntity>(entity).State = EntityState.Modified;
        }
        public override void RegisterDeleted<TEntity>(TEntity entity)
        {
            Db.Set<TEntity>().Remove(entity);
        }

        #region IUnitOfWork Support
        public override void BeginTransaction()
        {
            _dbTransaction = _context.Database.BeginTransaction();
           // base.Transaction = _dbTransaction.GetDbTransaction();
        }

        public override int Commit()
        {
            int result = 0;
            try
            {
                result = _context.SaveChanges();
                if (_dbTransaction != null)
                    _dbTransaction.Commit();
            }
            catch (Exception ex)
            {
                result = -1;
                _dbTransaction.Rollback();
                throw new Exception($"Commit 异常：{ex.InnerException}/r{ ex.Message}");
            }
            return result;
        }
        public override async Task<int> CommitAsync()
        {
            int result = 0;
            try
            {
                result = await _context.SaveChangesAsync();
                if (_dbTransaction != null)
                    _dbTransaction.Commit();
            }
            catch (Exception ex)
            {
                result = -1;
                _dbTransaction.Rollback();
                throw new Exception($"Commit 异常：{ex.InnerException}/r{ ex.Message}");
            }
            return await Task.FromResult(result);
        }
        public override void Rollback()
        {
            if (_dbTransaction == null)
                throw new ApplicationException("没有开启事务，不能回滚。");
            _dbTransaction.Rollback();
        }
        #endregion

        #region IDisposable Support
        protected override void Dispose(bool disposing)
        {
            if (_dbTransaction != null)
                _dbTransaction.Dispose();

            _context.Dispose();
            GC.SuppressFinalize(this);
        }
        #endregion
    }
}
